<?php
/**
 * Created by PhpStorm.
 * User: Zhoujinda
 * Date: 2016/5/16
 * Time: 16:19
 */
namespace Mengwu\Controller;

use Admin\Api\ConfigApi;
use Common\Api\AccountApi;
use Mengwu\Api\MwApi;
use Think\Controller;

abstract class BaseStoreController extends Controller{
    protected $themeType;
    protected $userinfo;

    protected $seo = [
        'title'=>'',
        'keywords'=>'',
        'description'=>''
    ];

    protected function _initialize() {
        $this->themeType = "desktop_default";
        C('SHOW_PAGE_TRACE', false);//设置不显示trace

        $this->userinfo = session('user');
        if(!empty($this->userinfo)){
            $user_info = [
                'id' => $this->userinfo['id'],
                'username' => $this->userinfo['username'],
                'nickname' => $this->userinfo['nickname'],
                'head' => $this->userinfo['head']
            ];
            $this->assign('user_info', $user_info);
        }

        // 获取配置
        $this -> getConfig();
        // 对页面一些配置赋值
        $this -> assignPageVars();

        //取购物车数据
        $this->addons_spcart();
    }
    
    protected function assignTitle($title){
        $this->seo = array_merge($this->seo,['title'=>$title]);
		$this->assign("seo",$this->seo);
    }
    protected function assignKeywords($keywords){
        $this->seo = array_merge($this->seo,['keywords'=>$keywords]);
        $this->assign("seo",$this->seo);
    }
    protected function assignDescription($description){
        $this->seo = array_merge($this->seo,['kdescription'=>$description]);
        $this->assign("seo",$this->seo);
    }

    protected function jump2login(){
        $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $url = urlencode($url);
        if(empty($this->userinfo)) redirect(U('mengwu/account/login').'?redirect='.$url);
    }

    /**
     * 使用指定风格模版
     */
    protected function boye_display($page=''){
        $this->theme($this->themeType)->display($page);
    }

    /**
     * 需要登陆的API
     */
    public function needLogin(){
        if(!$this->isLogin()){
            $url = 'http://'.$_SERVER['HTTP_HOST'].U('mengwu/account/login');
            if(!is_null($_SERVER['HTTP_REFERER'])) $url = $url.'?redirect='.urlencode($_SERVER['HTTP_REFERER']);
            $this->ajaxReturnErr(['info'=>'请先登录', 'redirect'=>$url]);
        }
    }

    /**
     * 是否登陆
     */
    protected function isLogin(){
        return !empty($this->userinfo);
    }

    /**
     * 页面必须刷新，禁止缓存
     */
    protected function noCachePage(){
        header("Cache-control:no-cache,no-store,must-revalidate");
        header("Pragma:no-cache");
        header("Expires:0");
    }

    /**
     * errorpage
     */
    protected function errorPage($errorInfo="页面错误"){
        $this->assign('error',$errorInfo);
        $this->boye_display('Public:error');
        exit();
    }

    /**
     * 取用户ID
     */
    protected function getUID(){
        if(!empty($this->userinfo)){
            return $this->userinfo['id'];
        }else{
            return -1;
        }
    }
    
    /**
     * 显示404页面
     */

    protected function display_404(){
        header("HTTP/1.0 404 Not Found");
        $this->theme($this->themeType)->display('Public:404');
        exit();
    }
    
    /**
     * ajax返回失败
     */
    protected function ajaxReturnErr($data){
        $this->ajaxReturn(['status'=>false, 'info'=>$data]);
    }

    /**
     * ajax返回成功
     */
    protected function ajaxReturnSuc($data){
        $this->ajaxReturn(['status'=>true, 'info'=>$data]);
    }

    /**
     * 根据status自动ajax返回
     */
    protected function apiReturn($result,$sucInfo=null,$errInfo=null){
        if(is_null($sucInfo)) $sucInfo = $result['info'];
        if(is_null($errInfo)) $errInfo = $result['info'];
        if($result['status']){
            $this->ajaxReturnSuc($sucInfo);
        }else{
            $this->ajaxReturnErr($errInfo);
        }
    }

    //页面上变量赋值
    public function assignPageVars(){
        $seo = array('title' => C('WEBSITE_TITLE'), 'keywords' => C('WEBSITE_KEYWORDS'), 'description' => C('WEBSITE_DESCRIPTION'));
        $this->seo = array_merge($this->seo,$seo);

        $this->assign("seo",$this->seo);
    }
    /**
     * 从数据库中取得配置信息
     */
    protected function getConfig() {
        $config = S('config_' . session_id() . '_' . session("uid"));

        if ($config === false) {
            $map = array();
            $fields = 'type,name,value';
            $result = apiCall(ConfigApi::QUERY_NO_PAGING, array($map, false, $fields));
            if ($result['status']) {
                $config = array();
                if (is_array($result['info'])) {
                    foreach ($result['info'] as $value) {
                        $config[$value['name']] = $this -> parse($value['type'], $value['value']);
                    }
                }
                //缓存配置300秒
                S("config_" . session_id() . '_' . session("uid"), $config, 300);
            } else {
                LogRecord('INFO:' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
                $this -> error($result['info']);
            }
        }
        C($config);
    }

    /**
     * 根据配置类型解析配置
     * @param  integer $type 配置类型
     * @param  string $value 配置值
     * @return array|string
     */
    private static function parse($type, $value) {
        switch ($type) {
            case 3 :
                //解析数组
                $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
                if (strpos($value, ':')) {
                    $value = array();
                    foreach ($array as $val) {
                        list($k, $v) = explode(':', $val,2);
                        $value[$k] = $v;
                    }
                } else {
                    $value = $array;
                }
                break;
        }
        return $value;
    }

    /**
     * 取购物车数据
     */
    protected function addons_spcart(){
        if($this->isLogin()){
            $data = [
                'uid' => $this->getUID(),
                'api_ver' => 101
            ];

            $result = mwApi(MwApi::BY_ShoppingCart_all,$data);

            $PICTURE_REMOTE_URL = C('PICTURE_REMOTE_URL');
            if($result['status']){
                $shore_list = $result['info']['store_list'];
                foreach($shore_list as &$val){
                    foreach($val['carts'] as &$val2){
                        $val2['icon_url'] = $PICTURE_REMOTE_URL.$val2['icon_url'].'&size=80';
                    }
                    $val['count'] = count($val['carts']);
                }

                $this->assign('addons_spcart',$shore_list[0]);
            }
        }

    }

    /**
     * 更新用户信息
     */
    protected function updateUserInfo(){
        if($this->isLogin()){
            $uid = $this->userinfo['id'];
            $result = apiCall(AccountApi::GET_INFO,[$uid]);
            if($result['status']){
                session('user',$result['info']);
            }
        }

    }

}